package main.com.sun.jeecgexam.struts.config;

import main.com.sun.jeecgexam.struts.mapping.ActionForward;
import main.com.sun.jeecgexam.struts.mapping.ActionMapping;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by sun on 2017/3/28.
 */
public class ConfigParseUtil {
    public static Map<String,ActionMapping> ParseStrutsConfig(String xmlpath){
        SAXReader reader = new SAXReader();
        try {


            Map<String, ActionMapping> map = new HashMap<String, ActionMapping>();
            Document dom = reader.read(new File(xmlpath));

            Element root = dom.getRootElement();


            Element formbeansElement = root.element("form-beans");
            Element actionsElement = root.element("actions");

            List<Element> formbeans = formbeansElement.elements("form-bean");
            List<Element> actionbeans = actionsElement.elements("action");


            for (Element formbean : formbeans) {
                ActionMapping mapping = new ActionMapping();
                mapping.setName(formbean.attribute("name").getValue());
                mapping.setFormClass(formbean.attribute("class").getValue());
                map.put(mapping.getName(), mapping);
            }


            for (Element actionbean : actionbeans) {
                ActionMapping mapping = map.get(actionbean.attributeValue("name"));
                mapping.setActionClass(actionbean.attributeValue("class"));

                List<Element> forwards = actionbean.elements("forward");
                for (Element forward : forwards) {
                    ActionForward newForward = new ActionForward();
                    newForward.setName(forward.attributeValue("name"));
                    newForward.setJspurl(forward.attributeValue("jspurl"));
                   mapping.addForward(newForward);
                }
            }


            return map;
        } catch (DocumentException e) {
            e.printStackTrace();
            return null;
        } catch (Exception e1) {
            e1.printStackTrace();
            return null;
        }
    }
}
